<template>
  <view
    :style="'height:' + (couponShow ? 600 : '') + 'px;overflow:' + (couponShow ? 'hidden' : 'auto') + ';padding-bottom:' + (couponShow ? '' : '60') + 'px;'">
    <view class="delivery" v-if="form.deliverType!=='LOGISTICS' && deliveryActions.length"
      @click="chooseDeliveryMethod">
      <view>
        <block>配送方式</block>
      </view>
      <view style="display:flex">
        物流配送
        <u-icon name="arrow-right" class="arrow"></u-icon>
      </view>
    </view>
    <block>
      <view class="address">
        <!-- 用户地址 -->
        <block v-if="miniAccountAddress.length">
          <view class="address__lead" @click.stop="goSelectAddress">
            <view class="address__lead--left">
              <u-icon name="map"></u-icon>
              <view style="margin-left:20rpx">{{miniAccountAddress[addressIndex].userName}}</view>
              <view style="margin-left:20rpx">{{miniAccountAddress[addressIndex].phone}}</view>
            </view>
            <view class="address__lead--right ">切换地址 ></view>
          </view>
        </block>
        <block v-else>
          <view class="address__empty" @click.stop="goSelectAddress">
            <view>请填写收货地址</view>
            <view>></view>
          </view>
          <view style="width:10px;height:10px"></view>
        </block>
        <image
          src="https://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/%E5%9B%BE%E6%A0%87/static/xian-fd12ebbd3d.png">
        </image>
      </view>
    </block>
    <view class="card">
      <view v-for="(item, index) in itemVoList" :key="index" class="card__good">
        <image :src="item.productSkuPic || item.productPic"></image>
        <view class="card__good--detail">
          <view class="goods--name">{{item.productName}}</view>
          <view class="card__good--detail--sec">{{item.specs}}</view>
          <view class="card__good--detail--sec" style="margin-top:40rpx">
            <view>数量 X {{item.productQuantity}}</view>
            <view class="price">￥{{item.productPrice}}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="priceCard">
      <view class="priceCard__price">
        <view class="item--label">商品总价</view>
        <view>￥{{totalPrice}}</view>
      </view>
      <view class="priceCard__coupon" v-if="couponItemShow">
        <view class="line--middle">
          <!-- <m-icon icon="icontijiaodingdan-youhuiquan" color="#F8D367" style="margin-right:10rpx"></m-icon> -->
          优惠券
        </view>
        <view class="priceCard__coupon--coupNum" @click="toggleCoupon">
          <block v-if="offerOptions.coupon">-￥{{offerOptions.coupon}}></block>
          <block v-else>
            <block v-if="helper.getCanUseCoupon(memberCoupons).length">
              <view>{{helper.getCanUseCoupon(memberCoupons).length}}张可用</view>
              <view class="arrow">></view>
            </block>
            <block v-else>
              <view style="color:#ccc">无可用优惠券</view>
            </block>
          </block>
        </view>
      </view>
      <view class="priceCard__coupon" v-if="offerOptions.fullScales">
        <view class="line--middle">
          <!-- <m-icon icon="icontijiaodingdan-manjian" color="blue" style="margin-right:10rpx"></m-icon> -->
          满减
        </view>
        <view class="priceCard__coupon--coupNum">-￥{{offerOptions.fullScales}}</view>
      </view>
      <view class="priceCard__code " v-if="canUseIntegralPrice && offerOptions.integralPrice">
        <view class="line--middle">
          <!-- <m-icon icon="iconshangpinxiangqing-jifen" color="#F17772" style="margin-right:10rpx"></m-icon> -->
          积分可抵扣
          <view class="priceCard__code--price">￥{{offerOptions.integralPrice}}</view>
        </view>
        <u-switch v-model="offerOptions.usetIntegral" size="20" activeColor="#FC425A"
          @change="onIntegralUseChnage"></u-switch>
      </view>
      <view class="priceCard__freight" v-if="!helper.isSelfPick(form.deliverType)">
        <block v-if="!offerOptions.freeShipping">
          <view>运费</view>
          <view>￥{{offerOptions.freightAmount}}</view>
        </block>
        <block v-else>
          <view>运费</view>
          <view>会员免运费</view>
        </block>
      </view>
      <view class="priceCard__all">
        <view>合计：</view>
        <view class="priceCard__all--price">￥{{realPrice}}</view>
      </view>
    </view>
    <!-- 会员 -->
    <block v-if="openMember>0 || !notIsVip">
      <view class="vip" v-if="offerOptions.giftIntegration || offerOptions.totalRebate">
        <view class="vip__top ">
          <view class="ifMember">
            <view style="margin-left:40rpx"></view>
            <view class="vip__top--num">
              <block>购买可获得{{offerOptions.giftIntegration}}积分</block>
              <block v-if="useRebate && offerOptions.totalRebate">
                ，返利￥{{offerOptions.totalRebate}}
              </block>
            </view>
          </view>
        </view>
      </view>
      <block v-if="offerOptions.reliefAmount">
        <!-- 非会员 -->
        <block v-if="notIsVip">
          <view class="vip">
            <view class="vip__top ">
              <view class="vip__top--sign">会员价</view>
              <view class="ifMember">
                <view style="margin-left:40rpx">
                  会员本单立省
                  <span class="vip__top--num">{{offerOptions.reliefAmount}}元</span>
                </view>
                <view class="vip__top--num" @click="becomeVip">立即购买</view>
              </view>
            </view>
          </view>
        </block>
        <!-- 会员 -->
        <block v-else>
          <view class="vip">
            <view class="vip__top ">
              <view class="vip__top--sign">会员价</view>
              <view class="ifMember">
                <view style="margin-left:40rpx">
                  会员本单立省
                  <span class="vip__top--num">{{offerOptions.reliefAmount}}元</span>
                </view>
                <view class="vip__top--num">-￥{{offerOptions.reliefAmount}}</view>
              </view>
            </view>
          </view>
        </block>
      </block>
      <!-- <view class="integral">
  <view class="integral__sign"></view>
  <view style="margin-left:10rpx">
    <block>购买可获得{{offerOptions.giftIntegration}}积分，</block>
    返利￥{{offerOptions.totalRebate}}
  </view>
</view> -->
    </block>
    <view class="form custom" v-if="forms.length">
      <custom-form id="customForm" ref="customForm" :forms="forms"></custom-form>
    </view>
    <view class="payWay">
      <u-radio-group v-model="form.payType">
        <u-cell-group>
          <u-cell v-if="userbalanceUseCondition" clickable name="BALANCE" @click="onPayTypeClick"
            :data-disabled="offerOptions.supplyBonus < realPrice">
            <view class="payWay__title" slot="title">
              <view class="van-cell-text">余额支付</view>
            </view>
            <u-radio slot="right-icon" activeColor="#FC425A" name="BALANCE"
              :disabled="offerOptions.supplyBonus < realPrice" @change="onPayTypeClick">
            </u-radio>
          </u-cell>
          <u-cell clickable name="WECHAT" @click="onPayTypeClick" >
            <view class="payWay__title" slot="title">
              <view class="van-cell-text">微信支付</view>
            </view>
            <u-radio slot="right-icon" activeColor="#FC425A" name="WECHAT" @change="onPayTypeClick"></u-radio>
          </u-cell>
        </u-cell-group>
      </u-radio-group>
    </view>
    <view class="submit">
      <view class=" submit__left">
        <view>合计：</view>
        <view class="submit__left--all ">
          <view>￥</view>
          <view style="font-size:40rpx">{{realPrice}}</view>
        </view>
      </view>
      <formid @click="handleSubmit">
        <button>提交订单</button>
      </formid>
    </view>
    <coupon-select :visible="couponShow" @onClose="toggleCoupon" :coupons="memberCoupons" @onSelect="onCouponSelect"
      state="use"></coupon-select>
    <view class="submit__mask" v-if="hasSubmited"></view>
  </view>
</template>

<script module="helper" lang="wxs" src="./helper.wxs"></script>
<script lang='ts'>
  import {
    Component,
    Vue
  } from 'vue-property-decorator'
  import {
    getConfirmOrder,
    createOrder,
    payment,
    getOrderStatus,
    getFreightAmount,
  } from "@/api";
  import sum from "lodash/sum";
  import formid from "@/components/formId/formId.vue"
  import customForm from "./custom-form/custom-form.vue"
  import couponSelect from '@/components/coupon-select/coupon-select.vue'
  import {
    IAdress,
    ICoupon,
    IProcuct,
    IFullScale,
    IFull,
    IMember,
    IRebateSet,
  } from "./interface";
  type PAYTYPE = 'WECHAT' | 'BALANCE' | 'FRIEND'


  @Component({
    components: {
      formid,
      customForm,
      couponSelect
    }
  })
  export default class Submit extends Vue {
    /** 支付方式 */
    payTypes: Array < any >= [{
        name: "余额支付",
        value: "BALANCE",
        icon: "iconbigeguanlitai-yiguanbi",
      },
      {
        name: "微信支付",
        value: "WECHAT",
        icon: "iconweixin",
      },
    ]

    /** 优惠券弹窗 */
    couponShow: boolean = false

    /** 优惠券选择项是否可见 */
    couponItemShow: boolean = true

    /** 积分翻倍 */
    integralValue: number = 1

    /** 配送方式 */
    deliveryActions: Array < any >= [
      {
        name: "物流配送",
        value: "LOGISTICS",
      },
    ]

    /** 自定义表单 */
    forms: Array < any >= []

    /** 提交的表单 */
    form = {
      // 优惠券ID
      couponId: 0,
      // 自定义表单
      customForm: "",
      // 配送方式 SELF_PICKUP, HOME_DELIVERY, LOGISTICS
      deliverType: "LOGISTICS",
      formId: "",
      // 满减活动ID
      fullScaleId: 0,
      // groupLeaderId
      groupLeaderId: "",
      // 使用积分抵扣
      integral: 0,
      itemDtoList: [],
      // 收货人地址ID
      miniAccountAddressId: "",
      // 用户留言
      userNote: "",
      orderType: "MALL",
      payType: 'WECHAT',
      sourceType: "MINI_PROGRAM",
      // 是否使用会员价
      useMemberPrice: false,
    }
    /** 优惠选项（本地计算用
     * 
     *  usetIntegral: 是否使用积分
     * 
     *  fullScales: 满减价格
     * 
     *  freightAmount: 配送费
     * 
     *  coupon: 优惠券价格
     * 
     *  integralPrice: 积分可抵扣价格
     * 
     *  giftIntegration: 可获取的积分
     * 
     *  reliefAmount: 商品会员减免价格
     * 
     *  freeShipping: 是否免运费
     * 
     *  totalRebate: 返利
     * 
     *  supplyBonus: 余额
     */

    offerOptions = {
      // 是否使用积分
      usetIntegral: false,
      // 满减价格
      fullScales: 0,
      // 配送费
      freightAmount: 0,
      // 优惠券价格
      coupon: 0,
      // 积分可抵扣价格
      integralPrice: 0,
      // 可获取的积分
      giftIntegration: 0,
      // 商品会员减免价格
      reliefAmount: 0,
      // 是否免运费
      freeShipping: false,
      // 返利
      totalRebate: 0,
      // 余额
      supplyBonus: 0,
    }
    /** 商品列表 */
    itemVoList: Array < IProcuct >= []
    /** 优惠券列表 */
    memberCoupons: Array < ICoupon >= [] = []
    /** 地址列表 */
    miniAccountAddress: Array < IAdress >= [] = []
    /** 满减数据 */
    fullScales: Array < any >= []
    /** 地址索引 */
    addressIndex: number = 0
    /** 真实价格 */
    realPrice: number = 0
    totalPrice: number = 0
    /** 积分 */
    integral: number = 0
    /** 满减规则 */
    discountInfoDto = {
      ceiling: 0,
      ratio: 0,
    }
    /** textarea 聚焦 */
    focus: boolean = false
    /** 是否第一次进入 */
    isFirst: boolean = true
    /** 选择地址页面选择后会设置这个值 */
    address: any = {}

    /** 是否已订阅，解决重复提交问题 */
    haSubscribed: boolean = false

    hasSubmited: boolean = false

    /** 上级路由，用于判断是否刷新数据 */
    prevRoute: any = null

    /** 当前用户是否为会员 */
    notIsVip: boolean = true

    /** 是否开启返利 */
    useRebate: boolean = true

    /** 是否开启余额支付 */
    userbalanceUseCondition: boolean = false

    /** 是否满足使用积分 */
    canUseIntegralPrice: boolean = true


    /** 非会员余额 */
    supplyBonus: number = 0

    dataFrom: string = "miniApp"
    timer: any = null;
    options: any = {}
    get openMember() {
      return this.$store.state.settingStore.shopSetting.openMember
    }
    onLoad(options) {
      // this.app.$pubsub.on("app-launch", () => {
      //   this.getShipperSetting();
      // });
      this.options = options;
      if (options.type && options.type === "h5") {
        this.dataFrom = options.type;
        this.$store.dispatch('userStore/login', 1).then(() => {
          this.$store.dispatch('settingStore/getSetting').then(() => {
            this.getOrderData(options);
          });
        });
      } else {
        this.getOrderData(options);

        this.$Pubsub.on("app-launch", () => {
          this.getOrderData(options);
        });
      }
    }
    onShow() {
      if (!this.isFirst) {
        this.getOrderData(this.options);
      }
    }

    onHide() {
      this.setData({
        isFirst: false
      });
    }

    onUnload() {
      clearInterval(this.timer);
    }
    onShareAppMessage() {
      const shopName = this.$store.state.shopset.shopInfo.shopName;
      return {
        title: shopName,
        path: "/pages/index/index?page=home",
        imageUrl: "",
      };
    }

    becomeVip() {
      uni.navigateTo({
        url: "/subcontract/pages/member/member"
      });
    }

    getPrevRoute() {
      try {
        const pages = getCurrentPages(); // eslint-disable-line
        return pages[pages.length - 2].route;
      } catch {
        return null;
      }
    }

    toggleFocus() {
      this.setData({
        focus: !this.focus
      });
    }

    /** 获取配送类型 */
    getShipperSetting() {
      const _form = this.form;
      return new Promise((resolve, reject) => {
          _form.deliverType = 'LOGISTICS'
          this.setData({
            deliveryActions: [{
              name: "物流配送",
              value: "LOGISTICS",
            } ],
            form: _form,
          });
          return resolve('1');
      });
    }
    /** 获取可获取多少积分 */
    getTotalGiftIntegration() {
      let _offerOptions = this.offerOptions
      _offerOptions.giftIntegration = sum(
        this.itemVoList.map(
          item =>
          item.giftIntegration *
          item.productQuantity *
          this.integralValue,
        ),
      )
      this.offerOptions = _offerOptions
    }
    /** 获取实际价格 */
    getRealPrice() {
      const {
        fullScales,
        coupon,
        usetIntegral,
        integralPrice,
        reliefAmount,
      } = this.offerOptions;
      return (
        (this.totalPrice*100000000) -
        (fullScales*100000000) -
        (coupon*100000000) -
        ((usetIntegral ? integralPrice : 0)*100000000) -
        ((this.notIsVip ? 0 : reliefAmount)*100000000)
      )/100000000;
    }
    /** 设置实际价格 */
    setRealPrice() {
      const {
        freeShipping,
        freightAmount,
      } = this.offerOptions;
      const realPrice = +this.getRealPrice().toFixed(2);
      const freight = (!this.notIsVip && freeShipping ? 0 : freightAmount)
      this.setData({
          realPrice: realPrice <= 0 ? (freight > 0 ? freight : 0.01) : ((realPrice*100000000) + (freight*100000000))/100000000
          // (!this.notIsVip && freeShipping ? 0.01 : (freightAmount > 0 ? freightAmount : 0.01)) : realPrice + (!this
          //   .notIsVip && freeShipping ? 0 : freightAmount),
        },
        () => {
          // 如果少于余额，使用微信支付
          if (this.realPrice > this.offerOptions.supplyBonus) {
            this.setData({
              ["form.payType"]: "WECHAT"
            });
          }
        },
      );
    }
    /** 设置总价格 */
    setTotalPrice() {
      const totalPrice = sum(
        this.itemVoList.map(item => {
          return item.productPrice * 1000000 * item.productQuantity;
        }),
      );

      this.setData({
        totalPrice: (totalPrice / 1000000).toFixed(2)
      }, () => {
        this.setRealPrice();
      });
    }

    /**
     *  轮训订单状态
     * @param orderId
     * @param cb
     */
    getOrderStatus(orderId, cb: any) {
      this.timer = setInterval(() => {
        getOrderStatus({
            orderId,
            items: JSON.parse(
              decodeURIComponent(
                this.options.items || this.getOrSetItemStorage(true),
              ),
            ),
          })
          .then(res => {
            // -1->秒杀失败;0->排队中;order->成功;
            if (res === -1) {
              clearInterval(this.timer);
              return this.$Popup.toast("下单失败，请重试");
            }
            if (res === 0) {
              return;
            }
            if (res) {
              clearInterval(this.timer);
              cb(res);
            }
          })
          .catch(err => {
            clearInterval(this.timer);
            this.$Popup
              .alert({
                title: "温馨提示",
                content: err || "订单状态获取失败",
              })
              .then(() => null);
          });
      }, 1500);
    }
    /**
     * 获取配送费
     * @param query
     */
    getFreightAmount(query: {
      addressId: string
    }): any {
        // 配送类型：1->物流模式（需要总金额、收货地址ID）
        const type = 1
        // 物流
          const addressData = this.miniAccountAddress[
            this.addressIndex
          ];

          // 如果没有地址数据 不发起请求
          if (!addressData) {
            return;
          }

          // 如果为物流模式 需要将addressId改为postCode
          const addressId = addressData.postCode;

          Object.assign(query, {
            amount: this.totalPrice,
            addressId,
            region: addressId,
            items: this.form.itemDtoList,
          });

        getFreightAmount({
            type,
            amount: this.totalPrice,
            ...query
          })
          .then(({
            cost,
            time
          }) => {
            if (cost === null || cost === -1) {
              return this.$Popup.toast("不在配送范围内");
            }
            this.setData({
                ["offerOptions.freightAmount"]: cost,
              },
              () => {
                this.setRealPrice();
              },
            );
          })
          .catch(err => {
            this.$Popup.toast(err || "运费获取失败");
          });
      
    }

    /** 计算返利 */
    calulateRebate(
      memberInfo: IMember,
      itemVos: IProcuct[],
      rebateSet: IRebateSet,
    ) {
      let rebateRatio = 0;
      if (
        (!memberInfo && rebateSet.rebateCondition.includes("0")) ||
        memberInfo
      ) {
        // 默认返利比例
        rebateRatio = rebateSet.rebateRatio / 100;
      }

      // 返利总价
      return sum(
        itemVos.map(item => {
          const data = (item.skuRebates || []).find(
            sItem => +sItem.skuId === +item.productSkuId,
          ) as any;
          let price = data && data.rebatePrice * item.productQuantity;

          // 折扣
          if (price && item.rebateType === 2) {
            price = +(
              (item.productPrice * item.productQuantity * price) /
              100
            ).toFixed(2);
            return price;
          }

          if (!price && price !== 0 && item.rebateType === 3) {
            price = item.productPrice * item.productQuantity * rebateRatio;
            return price;
          }

          // 不返利
          if (item.rebateType === 0) {
            price = 0;
          }
          return price;
        }),
      );
    }
    /** 计算会员价 */
    calculateMemberDiscount(
      memberInfo: IMember,
      itemVos: IProcuct[],
      topMemberCardInfo: IMember,
    ) {
      const rebateSet = this.$store.state.settingStore.shopSetting.rebateSet as IRebateSet;
      if (!memberInfo) {
        this.calculateMemberData(topMemberCardInfo, itemVos, rebateSet);
      } else {
        this.calculateMemberData(
          memberInfo,
          itemVos,
          rebateSet,
          memberInfo.state === 1 ? false : true,
        );
      }
    }
    /** 计算会员数据 */
    calculateMemberData(
      memberInfo: IMember,
      itemVos: IProcuct[],
      rebateSet: IRebateSet,
      notIsVip = true,
    ) {
      // ptype 1 商品折扣 2 包邮
      // 默认折扣
      const {
        defValue = 0
      } = (memberInfo.memberCardPrivileges.find(
        item => item.ptype === "1",
      ) || {});
      // 获取商品优惠后的总价
      const memberPriceList = itemVos.map(item => {
        let price = 0;

        const priceInfo = (item.memberPrices || []).find(rule => {
          return (
            +rule.memberLevelId ===
            (notIsVip ?
              +item.memberPrices[item.memberPrices.length - 1].memberLevelId :
              +memberInfo.rankCode)
          );
        });

        price = priceInfo && priceInfo.memberPrice;

        // 计算直接减免
        if (price && item.memberType === 1) {
          price = +(item.productQuantity * price).toFixed(2);
        }

        // 折扣
        if (price && item.memberType === 2) {
          price = +(
            (item.productPrice * item.productQuantity * price) /
            100
          ).toFixed(2);
        }

        // 统一设置
        if (price && item.memberType === 3) {
          price = (item.productPrice * item.productQuantity * defValue) / 100;
        }

        // 不使用会员价
        if (item.memberType === 0) {
          return item.productPrice * item.productQuantity;
        }

        if (!price && price !== 0) {
          price = (item.productPrice * item.productQuantity * defValue) / 100;
        }
        const fullData = this.getFullScalesPrice(
          this.fullScales,
          this.itemVoList,
        );
        if (!fullData.canUseMemberPrice && fullData.price > 0) {
          return item.productPrice * item.productQuantity;
        }

        return price;
      });
      const totalMemberPrice = sum(memberPriceList);

      // 实际减免价格
      const relPrice = +(this.totalPrice * 1000000 - totalMemberPrice * 1000000) / 1000000;
      // 获取减免金额
      const reliefAmount = totalMemberPrice ? relPrice.toFixed(2) : 0;
      // 是否免运费
      const freeShipping = !notIsVip &&
        !!(memberInfo.memberCardPrivileges || []).find(
          item => item.ptype === "2",
        );
      const useRebate =
        (notIsVip && rebateSet.rebateCondition.includes("0")) ||
        (!notIsVip && rebateSet.rebateCondition.includes("1"));
      const userbalanceUseCondition =
        (notIsVip && rebateSet.balanceUseCondition.includes("0")) ||
        (!notIsVip && rebateSet.balanceUseCondition.includes("1"));

      // 返利
      const totalRebate = useRebate ?
        this.calulateRebate(memberInfo, itemVos, rebateSet) :
        0;
      let _offerOptions = this.offerOptions
      _offerOptions.supplyBonus = memberInfo.supplyBonus ? memberInfo.supplyBonus : this.supplyBonus
      _offerOptions.reliefAmount = +reliefAmount
      _offerOptions.totalRebate = +totalRebate.toFixed(2)
      _offerOptions.freeShipping = notIsVip ? false : freeShipping
      this.setData({
          offerOptions: _offerOptions,
          notIsVip,
          useRebate,
          userbalanceUseCondition,
        },
        () => {
          this.setRealPrice();
        },
      );
    }
    /** 获取提交信息 */
    getOrderData({
      items = this.getOrSetItemStorage(true),
    }) {
      getConfirmOrder({
          items: JSON.parse(decodeURIComponent(items)),
          type: "MALL",
        })
        .then(res => {
          // 设置一系列数据
          this.setResToData(res, items);
        })
        .catch(err => {
          this.$Popup.toast(err || "结算页面信息获取失败");
        });
    }
    /** 将数据设置到data */
    setResToData(res: any, items: any) {
      const {
        miniAccountAddress,
        itemVoList,
        memberCoupons,
        fullScales,
        integral,
        discountInfoDto,
        memberInfo,
        topMemberCardInfo,
        supplyBonus,
      } = res;
      let integralValue = 1;
      if (memberInfo) {
        const itemMemberCardPrivilege = memberInfo.memberCardPrivileges.filter(
          item => item.ptype === "3",
        )[0];
        integralValue = itemMemberCardPrivilege ?
          itemMemberCardPrivilege.defValue :
          1;
      }

      // 设置items缓存做跳转回来使用
      this.getOrSetItemStorage(false, items);

      this.setData({
          miniAccountAddress,
          itemVoList,
          fullScales,
          integral,
          discountInfoDto,
          integralValue,
          supplyBonus,
          ["form.itemDtoList"]: JSON.parse(decodeURIComponent(items)),
        },
        async () => {
          try {

            this.setData({
              forms: this.getCustomFrom(),
              memberCoupons: this.judgeCouponCanuse(
                (memberCoupons as any) || [],
                (itemVoList as IProcuct[]) || [],
              ),
              prevRoute: this.getPrevRoute(),
            });

            await this.getShipperSetting();

            this.setAddressIndexAndId();

            this.setTotalPrice();

            // 计算满减金额
            const fullData = this.getFullScalesPrice(
              this.fullScales,
              this.itemVoList,
            );

            if (fullData.fullScaleId && !fullData.sharedUseCoupon) {
              this.setData({
                couponItemShow: false
              });
            }

            // 获取积分是否可用
            this.getIntegralStatus(fullData as any);

            // 设置可获取积分
            this.getTotalGiftIntegration();
            if (fullData.canUseMemberPrice) {}
            this.calculateMemberDiscount(
              memberInfo,
              itemVoList as any,
              topMemberCardInfo,
            );
          } catch (err) {
            this.$Popup.toast(err);
          }
        }
      );
    }
    getCustomFrom() {
      try {
        return JSON.parse(this.$store.state.settingStore.order.customFrom);
      } catch {
        return [];
      }
    }

    /**
     * 判断优惠券是否可用
     * @param coupons
     * @param goodsList
     */
    judgeCouponCanuse(coupons: ICoupon[], goodsList: IProcuct[]) {
      // 是否为满减优惠券
      const isFullReduction = (type: number) => {
        return type === 2 || type === 3;
      };

      // 判断门槛优惠券是否满足使用条件canUse
      const getFullReductionMeet = ({
        couponType,
        conditionAmount,
        products,
        productType,
      }: {
        couponType: number;
        conditionAmount: number;
        products: IProcuct[];
        productType: number;
      }) => {
        if (productType === 0) {
          products = goodsList;
        }

        const ids = products.map(item => item.productId);
        products = goodsList.filter(item => {
          return ids.includes(item.productId);
          // && item.productPrice * item.productQuantity >= conditionAmount
        });

        // 商品总价
        const total = sum(
          products.map(item => item.productPrice * item.productQuantity),
        );

        // 判断是否满足满减条件
        if (isFullReduction(couponType) && conditionAmount > total) {
          return {
            status: false,
            products
          };
        }

        return {
          status: !!products.length && true,
          products
        };
      };

      // 全部商品参与的优惠券的可用状态
      const getAllStatus = ({
        conditionAmount,
        couponType,
        productType
      }) => {
        const status = getFullReductionMeet({
          conditionAmount,
          products: goodsList,
          couponType,
          productType,
        });

        return status;
      };

      // 指定商品参与的优惠券的可用状态
      const getSpecifyStatus = ({
        couponProducts,
        conditionAmount,
        couponType,
        productType,
      }) => {
        // 如果为满减优惠券 并且总价少于满足条件 设置不可用
        const status = getFullReductionMeet({
          conditionAmount,
          products: couponProducts,
          couponType,
          productType,
        });
        // 优惠券可用的商品id
        return status;
      };

      // 排除商品不参与的优惠券的可用状态
      const getExcludeStatus = ({
        couponProducts,
        conditionAmount,
        couponType,
        productType,
      }) => {
        const ids = couponProducts.map(item => item.productId);
        const products = goodsList
          .filter(item => !ids.includes(item.productId))
          .map(item => ({
            productId: item.productId
          })) as any;
        const status = getFullReductionMeet({
          conditionAmount,
          products,
          couponType,
          productType,
        });
        return status;
      };

      return coupons.map(item => {
        // @ts-ignore
        const {
          status,
          products
        } = {
          0: getAllStatus,
          1: getSpecifyStatus,
          2: getExcludeStatus,
        } [item.productType](item);
        // @ts-ignore
        item.canUse = status;
        item.couponProducts = products;
        return item;
      });
    }
    /**
     * 优惠券方法
     * @param coupon 优惠券
     */
    calculateCoupon({
      couponType,
      couponProducts,
      discount,
      discountAmount,
      id,
    }: ICoupon) {
      if (!id) {
        this.setData({
          couponShow: true,
          ["offerOptions.coupon"]: false,
          ["form.couponId"]: 0,
        });
        return;
      }

      const ids = (couponProducts as Array < {
        productId: string
      } > ).map(
        item => item.productId,
      );
        console.log('ids',ids);
        
      const itemData = this.itemVoList
        .filter(item => ids.includes(item.productId))
        .sort((a, b) => {
        return b.productPrice*b.productQuantity - a.productPrice*a.productQuantity;
      });
      console.log('1111111111',itemData,this.itemVoList);
      

      if (!itemData) {
        return this.$Popup.toast("不满足使用条件");
      }

      // eslint-disable-next-line prefer-const
      let {
        productPrice,
        productQuantity
      } = itemData[0];
      // 折扣
      if (couponType === 0 || couponType === 2) {
        productPrice = +(
          (productPrice * productQuantity * 1000000 * ((10 - discount) / 10)) /
          1000000
        ).toFixed(2);
      }

      // 金额券
      if (couponType === 1 || couponType === 3) {
        productPrice =
          productPrice * productQuantity <= discountAmount ?
          productPrice * productQuantity :
          discountAmount;
      }
      this.setData({
        ["form.couponId"]: id,
        ["offerOptions.coupon"]: productPrice >= 0.01 ? productPrice.toFixed(2) : "0.00",
      });
    }
    /** 获取积分是否可用 */
    getIntegralStatus({
      useIntegral
    }: Partial < IFull > = {
      useIntegral: true
    }) {
      const {
        integral,
        discountInfoDto,
        totalPrice,
      } = this['_data'];
      const canDeduction = (totalPrice * 1000000 * (discountInfoDto.ceiling / 100)) / 1000000;
      const usedIntegral = (canDeduction * 1000000) / (discountInfoDto.ratio / 100) / 1000000;
      const status = usedIntegral <= integral;
      this.setData({
        canUseIntegralPrice: status,
        ["offerOptions.integralPrice"]: useIntegral ? (Math.ceil(canDeduction*100)/100).toFixed(2) : 0,
      });

      return {
        status,
        integral: usedIntegral,
        canDeduction,
      };
    }
    /**
     * 获取满减金额
     * @param fullScales
     * @param itemVoList
     */
    getFullScalesPrice(fullScales: IFullScale[], itemVoList: IProcuct[]) {
      // applyType 适用优惠：0-会员价 1-优惠劵 满减可以共用条件
      // deductionType 可用抵扣： 0-积分 为0时可共用
      // const usedCoupon = true;
      // const usedMemberPrice = true;
      const [
        maxItem = {
          fullScaleId: null,
          price: 0,
          canUseMemberPrice: false,
          useIntegral: true,
          sharedUseCoupon: true,
        },
      ] = (fullScales || [])
      .map(
          ({
            fullScaleProducts,
            deductionType,
            applyType,
            productType,
            fullScaleRules,
          }) => {
            // 适用商品： 0-全部商品参与 1-指定商品参与 2-指定商品不参与
            // 是否能与积分共用
            const sharedUseIntegral = !!deductionType;
            // 是否能与会员价共用
            const sharedUseMemberPrice = applyType.includes("0");
            // 是否能与优惠券共用
            const sharedUseCoupon = applyType.includes("1");

            // 满足条件产品Id组
            const productIds = (productType === 0 ?
                itemVoList :
                fullScaleProducts
              )
              // @ts-ignore
              .map(p => p.productId);

            // 从所有商品中获取Id组内的商品 productType为2时 为指定商品不参数 做排除
            const product = itemVoList
              .filter(p =>
                productType !== 2 ?
                productIds.includes(p.productId) :
                !productIds.includes(p.productId),
              )
              .sort((a, b) => {
                return b.productPrice - a.productPrice;
              });

            // 商品总价
            const totalPrice = sum(
              product.map(p => p.productPrice * p.productQuantity),
            );

            // 获取优惠价格的数据
            const priceGroup = fullScaleRules
              .sort((a, b) => {
                let aPrice: number;
                let bPrice: number;

                if (a.ruleType === 0) {
                  aPrice = a.discountAmount;
                } else {
                  aPrice = +(
                    (totalPrice * 1000000 * ((10 - a.discount) / 10)) /
                    1000000
                  ).toFixed(2);
                }

                if (b.ruleType === 0) {
                  bPrice = b.discountAmount;
                } else {
                  bPrice = +(
                    (totalPrice * 1000000 * ((10 - b.discount) / 10)) /
                    1000000
                  ).toFixed(2);
                }

                return bPrice - aPrice;
              })
              .filter(rule => {
                return rule.conditionAmount <= totalPrice;
              })
              .map(({
                ruleType,
                discountAmount,
                discount,
                fullScaleId
              }) => {
                // 满减劵
                if (ruleType === 0) {
                  return {
                    fullScaleId,
                    price: discountAmount,
                    canUseMemberPrice: sharedUseMemberPrice,
                    useIntegral: sharedUseIntegral,
                    sharedUseCoupon,
                  };
                }

                // 满折劵
                if (ruleType === 1) {
                  return {
                    fullScaleId,
                    price: +(
                      (totalPrice * 1000000 * ((10 - discount) / 10)) /
                      1000000
                    ).toFixed(2),
                    canUseMemberPrice: sharedUseMemberPrice,
                    useIntegral: sharedUseIntegral,
                    sharedUseCoupon,
                  };
                }

                return {
                  fullScaleId,
                  price: 0,
                  canUseMemberPrice: sharedUseMemberPrice,
                  useIntegral: sharedUseIntegral,
                  sharedUseCoupon,
                };
              })
              .filter(item => !!item);

            const fullData = priceGroup[0] || {
              fullScaleId: null,
              price: 0
            };

            // 返回优惠金额
            return {
              ...fullData,
              canUseMemberPrice: sharedUseMemberPrice,
              useIntegral: fullData.fullScaleId ? sharedUseIntegral : true,
              sharedUseCoupon,
            };
          },
        )
        .sort((a, b) => {
          return b.price - a.price;
        });

      this.setData({
        ["form.fullScaleId"]: maxItem.fullScaleId,
        ["offerOptions.fullScales"]: maxItem.price,
      });

      return maxItem;
    }
    getOrSetItemStorage(isGet = false, items ? : any) {
      if (isGet) {
        return uni.getStorageSync("order-items") || items;
      }

      uni.setStorageSync("order-items", items || this.options.items);
    }
    /** 获取或者设置数据缓存 */
    getOrsetStorage(isGet = false): any {
      try {
        const keys = [
          "form",
          "itemVoList",
          "memberCoupons",
          "miniAccountAddress",
          "addressIndex",
        ];
        const data = {};
        const storageData = JSON.parse(uni.getStorageSync("submitData"));
        const setData = store => {
          keys.forEach(key => {
            data[key] = store[key];
          });
        };

        if (isGet) {
          if (storageData) {
            uni.getStorageSync("submitData");
            setData(storageData);
            return data;
          } else {
            return {};
          }
        }
        //   FIXME 订单信息存储
        //   setData(this.data);
        //   return uni.setStorageSync("submitData", JSON.stringify(data));
      } catch (err) {
        return false;
      }
    }
    verificationForm() {
      // const formComponent = document.getElementById("customForm") as any;
      const formComponent = this.$refs.customForm as any;
      return formComponent.verificationForm();
    }

    handleVerification() {
      const formComponent = this.$refs.customForm as any;
      // 自定义表单验证
      if (!formComponent || !formComponent.verificationForm()) {
        return false;
      }

      const addressData = this.miniAccountAddress[this.addressIndex];
      if (!addressData || !addressData.id) {
        this.$Popup.alert({
          title: "温馨提示",
          content: "请添加地址"
        }).then(() => {
          this.goSelectAddress();
        });
        return false;
      }

      return true;
    }
    /**
     * 提交订单
     * BALANCE WECHAT FRIEND
     */
    async handleSubmit({
      formId
    }) {
      try {
        if (!this.handleVerification() || this.hasSubmited) {
          return;
        }
        this.setData({
          hasSubmited: true
        });
        const formComponent = this.$refs.customForm as any;

        if (!this.haSubscribed) {
          /** 模板订阅 */
          await this.$store.dispatch("message/subscribe", [
            this.$store.state.message.type.sendMsg,
            this.$store.state.message.type.memberCartOpen,
          ])
          this.setData({
            haSubscribed: true
          });
        }

        /** 如果是从H5进入小程序支付订单 删除activityId 添加solitaireActivityId */
        if (this.dataFrom === "h5") {
          this.form.itemDtoList.forEach((inItem: any) => {
            inItem.solitaireActivityId = inItem.activityId;
            delete inItem.activityId;
          });
        }

        const {
          id
        } = this.miniAccountAddress[this.addressIndex];
        // 创建订单
        const orderId = await createOrder(
          Object.assign(this.form, {
            formId,
            groupLeaderId: this.form.groupLeaderId || "",
            groupLeaderNickname: "",
            pointAuthor: "",
            point_phone: "",
            miniAccountAddressId: id,
            customForm: formComponent ?
              JSON.stringify(formComponent.localForms) : "",

            deliveryTemplateId: await this.$store.dispatch("message/getTemplateId", this.$store.state.message.type
              .sendMsg) || null,
            memberTemplateId: await this.$store.dispatch("message/getTemplateId", this.$store.state.message.type
              .memberCartOpen) || null,
            useMemberPrice: !!this.offerOptions.reliefAmount,
            solitaireActivityId: this.form.itemDtoList[0].solitaireActivityId ?
              this.form.itemDtoList[0].solitaireActivityId : null,
          }),
        );

        // 轮训订单状态
        this.getOrderStatus(orderId, async () => {
          this.handleSubmitType(orderId)
            .then(() => null)
            .catch(err => {
              this.$Popup.toast(err || "支付失败");
              this.setData({
                hasSubmited: false
              });
            });
        });
      } catch (err) {
        this.setData({
          hasSubmited: false
        });
        this.$Popup.alert({
          title: "温馨提示",
          content: err || "订单状态获取失败",
        });
      }
    }

    /** 处理付款类型 */
    handleSubmitType(orderId) {
      switch (this.form.payType) {
        case "BALANCE":
          return this.balancePayment(orderId);
        case "WECHAT":
          return this.payment(orderId);
        case "FRIEND":
          return Promise.resolve(this.$Popup.toast("FRIEND"));
        default:
          return Promise.resolve();
      }
    }
    balancePayment(orderId) {
      return this.$Popup
        .modal({
          title: "温馨提示",
          content: "确认使用余额支付吗？"
        })
        .then(() => {
          return payment(orderId, true)
            .then(() => {
              return this.orderSuccess(orderId);
            })
            .catch(err => {
              this.$Popup.toast(err || "支付失败");
            });
        })
        .catch(() => {
          payment(orderId, false)
            .then(() => {
              return this.orderSuccess(
                orderId,
                () => uni.redirectTo({
                  url: "/subcontract/pages/order/order"
                }),
                false,
              );
            })
            .catch(err => {
              this.$Popup.toast(err);
            });
        });
    }
    /** 支付 */
    payment(orderId) {
      // return mockPay(orderId).then(res => {
      //   wx.redirectTo({ url: "/pages/order/order" });
      // });
      return payment(orderId)
        .then(res => {
          this.wecharPay(res.wxResult, orderId);
        })
        .catch(err => {
          this.$Popup.toast(err || "支付失败");
        });
    }
    /** 下单成功操作 */
    orderSuccess(orderId, cb ? , succ = true) {
      succ && this.$Popup.toast("支付成功");
      if (cb) return cb();
      const arr = JSON.parse(
        decodeURIComponent(this.options.items || this.getOrSetItemStorage(true)),
      );
      const number = arr.reduce((prev, item) => {
        return prev + item.number;
      }, 0);
        return uni.redirectTo({
          url: `/subcontract/pages/orderSuccess/orderSuccess?price=${this.realPrice}&orderId=${orderId}&totalRebate=${this.offerOptions.totalRebate}&number=${number}`,
        });
    }
    /** 微信支付 */
    wecharPay(res: any, orderId) {
      const isCancel = msg => msg.includes("cancel");
      uni.requestPayment({
        timeStamp: res.timeStamp,
        nonceStr: res.nonceStr,
        package: res.packageValue,
        signType: res.signType,
        paySign: res.paySign,
        success: () => {
          this.orderSuccess(orderId);
        },
        fail: e => {
          clearInterval(this.timer);

          // 如果为取消 跳至订单详情
          if (isCancel(e.errMsg)) {
            return uni.redirectTo({
              url: `/subcontract/pages/order/order?type=0`,
            });
          }
          this.$Popup.toast("支付失败");
        },
      });
    }

    /** 前往选择地址 */
    goSelectAddress() {
      this.getOrsetStorage();
      uni.navigateTo({
        url: `/subcontract/pages/address/address?redirect=${encodeURIComponent(
        `/modules/pages/submit/submit`,
      )}`,
      });
    }

    /** 设置地址索引 */
    setAddressIndexAndId() {
      const defaultAddressIndex = this.miniAccountAddress.findIndex(item => {
        return item.isDefault === 1;
      });
      const addressIndex = this.miniAccountAddress.findIndex(item => {
        return item.id === this.address.id;
      });
      const index = addressIndex >= 0 ? addressIndex : defaultAddressIndex;
      const addressData = this.miniAccountAddress[index];
      const id = addressData ?
        this.form.deliverType === "LOGISTICS" ?
        addressData.id :
        addressData.postCode :
        "";

      this.setData({
          addressIndex: index,
          [`form.miniAccountAddressId`]: id,
        },
        () => {
          // 获取运费
          this.getFreightAmount({
            addressId: id ? id : "",
          });
        },
      );
    }
    /**
     * 显示隐藏优惠券
     */
    toggleCoupon() {
      // if (this.data.memberCoupons.length === 0) {
      //   this.data.couponShow = true;
      // }
      this.setData({
        couponShow: !this.couponShow
      });
    }

    /** 选择优惠券 */
    onCouponSelect(item: ICoupon | null) {
      if (item.id && !item.canUse) {
        return this.$Popup.toast("优惠券不可用");
      }
      this.calculateCoupon(item);
      this.setRealPrice();
      this.toggleCoupon();
    }

    /** 支付方式选择 */
    onPayTypeClick(e) {
       let _form = this.form
      if(e.name){
        _form.payType = e.name
      }else{
        _form.payType = e
      }
      this.form = _form
    }
    /** 是否使用积分change */
    onIntegralUseChnage(e) {
      const {
        status,
        integral,
        canDeduction
      } = this.getIntegralStatus();

      if (!status || canDeduction < 0.01) {
        this.setData({
          ["offerOptions.usetIntegral"]: false
        })
        return this.$Popup.toast("不满足使用条件");
      }
      this.setData({
          ["offerOptions.usetIntegral"]: e,
          ["form.integral"]: e?+integral.toFixed(2):"0.00",
        },
        () => {
          this.setRealPrice();
        },
      );
    }

    /** 更新表单数据 */
    onFormChange({
      currentTarget: {
        dataset: {
          key
        },
      },
      detail: {
        value
      },
    }) {
      this.setData({
        [`form.${key}`]: value
      });
    }
    /**
     * 关闭底部弹窗
     */
    onClose() {
      this.setData({
        couponShow: false
      });
    }
  }
</script>
<style lang="scss" scoped>
  @import "@/assets/styles/submit/submit.scss";
</style>